<?php

if (!defined('IN_XLP')) {
        exit('Access Denied!');
}

/**
 * Description of event
 * 微信平台活动封装处理类
 * @author xlp
 */
class eventApi {

        public $info;
        public $text = ''; //输入内容

        function __construct(&$info) {
                $this->info = $info;
                if (!isset($this->info['city_id'])) {
                        $this->info['city_id'] = 0;
                }
        }

        //回复互动
        function replyEvent($id) {
                $rs = $this->getEventDetailData($id);
                if ($rs) {
                        //判断时间截点
                        if ($rs['isOver']) {
                                return ($rs['stime'] > TIME ? '游戏将于' . outTime($rs['stime']) . '正式开始' : '您来晚了，游戏已经结束...');
                        }
                        if ($rs['type'] != 4) {//优惠券、抽奖、刮刮卡、翻牌等
                                return "欢迎参加“" . $rs['title'] . "”\n活动说明：" . $rs['content']
                                        . "\n--------\n <a href=\"" . U('game/prize/detail', array('id' => $rs['id'])) . "\">点击开始咯~>></a>";
//                return array('type' => 'news', 'items' => array(array(
//                            'title' => $rs['title'],
//                            'description' => $rs['content'],
//                            'picurl' => BASE_URL . 'upload/pics/d-0' . $rs['type'] . '.jpg',
//                            'url' => U('prize/detail', array('id' => $rs['id'], 'code' => $this->info['code']))
//                )));
                        } else {//互动答题
                                //缓存记录,初始化各个参数
                                $cache = array(
                                  'act' => 'inter',
                                  'id' => $rs['id'],
                                  'stime' => TIME,
                                  'now' => 0,
                                  'isok' => 0,
                                  'iserror' => 0,
                                  'total' => $rs['setting']['total_inter'] - 1,
                                  'isBegin' => false
                                );
                                cacheApi::set($this->info['key'], $cache, 60 * 10);
                                $status = $this->checkInterStatus($rs, $cache);
                                if (!$status['status']) {
                                        return $status['info'];
                                }
                                //读取配置文件
                                $this->eventConfig = C('replyEvent_' . $rs['id']);
                                $note = '';
                                if (isHave($this->eventConfig['title'])) {
                                        $note = $this->eventConfig['title'];
                                }
                                if (isHave($this->eventConfig['content'])) {
                                        $note.=$this->eventConfig['content'];
                                }
                                if (!$note) {
                                        $note = "欢迎进入 " . $rs['title'] . " 互动答题环节！本活动共有" . $rs['setting']['total_inter'] . "个题目\n活动说明："
                                                . $rs['content'] . "\n--------\n请按以下提示进行操作：\n回复“开始”进入活动，回复“退出”结束活动，\n注意：请回复答案对应编号即可。";
                                }
                                return $note;
                        }
                }
                return '抱歉，内容不存在';
        }

        //抽奖相关
        function getEventDetailData($id, $checkTims = true, $checkAid = true) {
                if (!$id) {
                        return false;
                }
                $where = '';
                if ($checkAid) {
                        $where = ' AND a.aid=' . $this->info['aid'];
                }
                $sql = 'SELECT '
                        . 'a.id,a.aid,a.title,a.type,a.times,a.everyday,a.shares,a.hasbind,a.share_title,a.share_content,a.stime,a.etime,a.keyword,a.recontent,a.attend,a.partic,b.itemid,b.skin_path,b.picurl,b.content,b.setting'
                        . ' FROM __TABLE__ AS a '
                        . 'LEFT JOIN __PRE__event_item AS b ON a.id=b.id WHERE a.id=' . $id . $where . ' LIMIT 1';
                $rs = M('event')->query($sql, true);
                if (!$rs) {
                        return false;
                }
                //解析奖品信息
                if ($rs['setting']) {
                        $rs['setting'] = json_decode($rs['setting'], true);
                }
                //是否绑定帐号
                $rs['isBind'] = $this->info['isBind'];
                //判断时间截点
                $rs['isBegin'] = $rs['stime'] <= TIME ? 1 : 0;
                $rs['isOver'] = $rs['etime'] < TIME ? 1 : 0;
                if ($checkTims) {
                        //查询当前帐号参与抽奖次数
                        $rs['hasTimes'] = 1;
                        if ($rs['times']) {
                                if ($rs['isBind']) {
                                        $rs['times']+=$rs['hasbind'];
                                }
                                $rs['remainTimes'] = $rs['times'] - M('prize')->where(array('aid' => $this->info['aid'], 'id' => $rs['id'], 'uid' => $this->info['uid']))->count('pid');
                                if ($rs['remainTimes'] <= 0) {
                                        $rs['remainTimes'] = 0;
                                        $rs['hasTimes'] = 0;
                                }
                        } else {
                                $rs['remainTimes'] = 0;
                        }
                        //判断每日允许次数
                        $rs['hasEveryday'] = 1;
                        if ($rs['everyday']) {
                                $stime = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
                                $etime = mktime(0, 0, 0, date('m'), date('d') + 1, date('Y')) - 1;
                                if ($rs['isBind']) {
                                        $rs['everyday']+=$rs['hasbind'];
                                }
                                $rs['remainEveryday'] = $rs['everyday'] - M('prize')->where("aid=" . $this->info['aid'] . " AND id=" . $rs['id'] . " AND uid=" . $this->info['uid'] . " AND infotime>=" . $stime . " AND infotime<=" . $etime)->count('pid');
                                if ($rs['remainEveryday'] <= 0) {
                                        $rs['remainEveryday'] = 0;
                                        $rs['hasEveryday'] = 0;
                                }
                        } else {
                                $rs['remainEveryday'] = 0;
                        }
                        //判断分享新增次数
                        $rs['hasShares'] = 0;
                        if ($rs['shares']) {
                                $count = M('user_share')->field('is_used')->where(array('aid' => $this->info['aid'], 'fid' => $rs['id'], 'uid' => $this->info['uid'], 'type' => 2))->find();
                                if (isset($count['is_used'])) {//有过分享记录
                                        $rs['remainShares'] = $rs['shares'] - $count['is_used'];
                                        $rs['hasShares'] = 1;
                                } else {
                                        $rs['remainShares'] = $rs['shares'];
                                        $rs['hasShares'] = 0;
                                }
                                if ($rs['remainShares'] <= 0) {
                                        $rs['remainShares'] = 0;
                                        $rs['hasShares'] = 0;
                                }
                        } else {
                                $rs['remainShares'] = 0;
                        }
                }
                return $rs;
        }

        //计算中奖
        function getLuckData($rs) {
                $noRate = array('name' => '', 'gift' => '', 'credit' => 0, 'ticket_id' => 0, 'count' => 0, 'rate' => 1, 'content' => ''); //未中奖的  抵价券添加
                $isprize = 0; //默认不中奖
                $prize = $noRate;
                $code = ''; //随机生成号码
                $totalCount = isset($rs['setting']['total']) ? $rs['setting']['total'] : 0;
                if ($totalCount) {
                        $rateArr = array();
                        foreach ($rs['setting']['item'] as $val) {
                                $rateArr[] = $val['rate'];
                                $noRate['rate']-=$val['rate'];
                        }
                        if ($noRate['rate'] < 0) {
                                $noRate['rate'] = 0;
                        }
                        if ($noRate['rate'] > 0) {//没有指定未中奖，则剩余比率全为未中奖
                                $rateArr[] = $noRate['rate'];
                                $itemArr = array_merge($rs['setting']['item'], array($noRate));
                        } else {
                                $itemArr = $rs['setting']['item'];
                        }
                        $prizeId = getRand($rateArr, 3);
                        $prize = isset($itemArr[$prizeId]) ? $itemArr[$prizeId] : $noRate;
                        //统计当前抽中项的中奖人数
                        if ($prize['name']) {
                                //统计所有已中奖的人数
                                $totalPrize = M('prize')->where('aid=' . $this->info['aid'] . ' AND id=' . $rs['id'] . " AND prize<>''")->count('pid');
                                //统计当前奖项已中奖人数
                                $nowPrize = M('prize')->where(array('aid' => $this->info['aid'], 'id' => $rs['id'], 'prize' => $prize['name']))->count('pid');
                                //如果当前已中奖人数大于规定的总人数或者当前已中奖人数大于奖项规定人数则本次抽奖无效
                                if (($totalPrize >= $totalCount) || ($prize['count'] && $nowPrize >= $prize['count'])) {
                                        $prize = $noRate;
                                        $isprize = 0;
                                        $code = '';
                                } else {//记录本次抽奖数据
                                        if (in_array($rs['id'], array(53))) {//发放小管家优惠券
                                                $coupon = D('steCoupon')->addRandCoupon($this->info['uid'], $this->info['city_id'], 1, $rs['id'], $prize['name'], 0);
                                                if ($coupon['status'] == 1) {
                                                        $code = $coupon['rs']['coupon_code'];
                                                        $isprize = $prizeId + 1;
                                                } else {
                                                        $prize = $noRate;
                                                        $isprize = 0;
                                                        $code = '';
                                                }
                                                $credit = isset($prize['credit']) ? $prize['credit'] : 0;
                                        } elseif ($rs['type'] == 17) {//扫码领券
                                                $data = array(
                                                  'stype' => 1,
                                                  'smod' => $rs['id'],
                                                  'city_id' => 3301,
                                                  'coupon_title' => $prize['gift'],
                                                  'coupon_code' => D('steCoupon')->getCouponCode(),
                                                  'start_amount' => priceFormat($rs['setting']['custom']['start_amount']),
                                                  'coupon_money' => priceFormat($prize['name']),
                                                  'used_uid' => $this->info['uid'],
                                                  'start_time' => inTime($rs['setting']['custom']['start_time']),
                                                  'end_time' => inTime($rs['setting']['custom']['end_time']),
                                                  'info_time' => TIME
                                                );
                                                if (D('steCoupon')->addPrizeCoupon($data)) {
                                                        $code = $data['coupon_code'];
                                                        $isprize = $prizeId + 1;
                                                } else {
                                                        $prize = $noRate;
                                                        $isprize = 0;
                                                        $code = '';
                                                }
                                                $credit = isset($prize['credit']) ? $prize['credit'] : 0;
                                        } elseif ($prize['ticket_id']) {
                                                $ticket=$rs['setting']['ticket'];
                                                $data = array(
                                                  'stype' => 1,
                                                  'smod' => $rs['id'],
                                                  'city_id' => 3301,
                                                  'coupon_title' => $prize['gift'],
                                                  'coupon_code' => D('steCoupon')->getCouponCode(),
                                                  'start_amount' => priceFormat($ticket[$prize['ticket_id']]['ticket_amount']),
                                                  'coupon_money' => priceFormat($ticket[$prize['ticket_id']]['ticket_money']),
                                                  'used_uid' => user::$userInfo['uid'],
                                                  'start_time' =>TIME,
                                                  'end_time' =>(TIME+60*60*24*$ticket[$prize['ticket_id']]['ticket_day']),
                                                  'info_time' => TIME
                                                );
                                                if (D('steCoupon')->addPrizeCoupon($data)) {
                                                        $code = $data['coupon_code'];
                                                        $isprize = $prizeId + 1;
                                                } else {
                                                        $prize = $noRate;
                                                        $isprize = 0;
                                                        $code = '';
                                                }
                                                $credit = isset($prize['credit']) ? $prize['credit'] : 0;
                                        } else {
                                                $code = getRandInt(15, 1);
                                                $isprize = $prizeId + 1;
                                                $credit = isset($prize['credit']) ? $prize['credit'] : 0;
                                        }
                                        if ($credit) {
                                                //临时的 根据id判断是不是发放结邻币
                                                if (in_array($rs['id'], array(45))) {
                                                        //送出结邻币
                                                        D('member')->setUserScore(array('uid' => $this->info['uid'], 'act' => 1, 'event' => 2, 'fid' => $rs['id'], 'credit' => $credit, 'content' => '参加活动' . $rs['title'] . ':' . $prize['name']), 'shopping');
                                                        //临时的 根据活动类型判断是不是发放现金红包
                                                } elseif ($rs['type'] == 19) {
                                                        //送出现金红包
                                                        T('weixin/weixin.redpack');
                                                        $redpack = new weixinRedpack();
                                                        $redpackinfo['send_name'] = '结邻公社';
                                                        $redpackinfo['wishing'] = $rs['content'];
                                                        $redpackinfo['act_name'] = $rs['title'];
                                                        $redpackinfo['re_openid'] = D('member')->getOpenidByUids($this->info['uid']);
                                                        $redpackinfo['num'] = 1;
                                                        //金额
                                                        $redpackinfo['money'] = (int) $credit;
                                                        $result = $redpack->send($redpackinfo);
                                                        //如果接口通知失败，仍然将此次抽奖当做失败处理，且不记入状态，防止用户再无法抽奖
                                                        if (!$result) {
                                                                $prize = $noRate;
                                                                $isprize = 0;
                                                                $code = '';
                                                        }
                                                } else {
                                                        //送出积分
                                                        D('member')->setUserScore(array('uid' => $this->info['uid'], 'act' => 1, 'event' => 2, 'fid' => $rs['id'], 'credit' => $credit, 'content' => '参加' . $rs['title'] . ':' . $prize['name']));
                                                }
                                        }
                                }
                        }
                }
                if (!$prize['name'] && $rs['type'] == 19) {
                        return array('isprize' => $isprize, 'prize' => $prize['name'], 'gift' => $prize['gift'], 'code' => $code, 'content' => $prize['content']);
                }
                $this->setUserPrizeInfo(array('id' => $rs['id'], 'code' => $code, 'prize' => $prize['name']));
                return array('isprize' => $isprize, 'prize' => $prize['name'], 'gift' => $prize['gift'], 'code' => $code, 'content' => $prize['content']);
        }

        function setUserPrizeInfo($info) {
                //判断是否第一次参加
                if (!M('prize')->field('pid')->where(array('aid' => $this->info['aid'], 'uid' => $this->info['uid'], 'id' => $info['id']))->find()) {
                        M('event')->where(array('id' => $info['id'], 'aid' => $this->info['aid']))->setInc('partic', 1); //活动参与人数 
                }
                M('prize')->insert(array('id' => $info['id'], 'aid' => $this->info['aid'], 'code' => $info['code'], 'uid' => $this->info['uid'], 'prize' => $info['prize'], 'status' => 0, 'infotime' => TIME));
                M('event')->where(array('id' => $info['id'], 'aid' => $this->info['aid']))->setInc('attend', 1); //活动参与人数
                return true;
        }

        function getInterData($text = '', &$cache) {
                //读取配置文件
                $flag = 0; //是否星标消息
                $this->eventConfig = C('replyEvent_' . $cache['id']);
                $rs = $this->getEventDetailData($cache['id']);
                if ($cache['iserror']) {//存在错误回答的情况，看用户是否愿意复活
                        if ($text == '复活') {//复活，游戏从头开始
                                $cache['iserror'] = 0;
                                $cache['isok'] = 0;
                                $cache['now'] = 0;
                                $text = '开始';
                        } elseif ($text == '退出') {//退出，结束并清除游戏数据
                                cacheApi::delete($this->info['key']);
                                $note = '您已退出微信互动答题游戏';
                        } else {
//                cacheApi::delete($this->info['key']);
                                return '您尚在互动游戏进程中，回复“复活”继续游戏；回复“退出”结束并保存游戏进度';
                        }
                }
                if ($text == '开始' || $text == 'go' || $text == 'GO') {
                        if ($cache['now'] > 0) {
                                return '您已经开始游戏啦，请直接回答问题...';
                        }
                        $status = $this->checkInterStatus($rs, $cache);
                        if (!$status['status']) {
                                cacheApi::delete($this->info['key']);
                                return $status['info'];
                        }
//            elseif ($this->eventConfig && $this->eventConfig['everyDayTimes'] && M('prize')->where("aid=" . $this->info['aid'] . " AND id=" . $rs['id'] . " AND uid=" . $this->info['uid'] . " AND infotime>=" . $this->eventConfig['stime'] . " AND infotime<=" . $this->eventConfig['etime'])->count('pid') >= $this->eventConfig['everyDayTimes']) {
//                cacheApi::delete($this->info['key']);
//                return $this->eventConfig['no_chance'];
//            } 
                        else {
                                //标记游戏开始
                                $cache['isBegin'] = true;
                                cacheApi::set($this->info['key'], $cache, 60 * 10);
                                $note = $rs['setting']['item_inter'][$cache['now']]['name'];
                        }
                } elseif ($text == '退出') {
                        if ($cache['now'] > 0) {
                                //记录参与游戏
                                $this->setUserPrizeInfo(array('id' => $rs['id'], 'code' => '', 'prize' => ''));
                        }
                        cacheApi::delete($this->info['key']);
                        $note = '您已退出微信互动答题游戏';
                } else {
                        //检查
                        if (!$cache['isBegin']) {
                                return '额，您好像没有遵守游戏规则，请先回复“开始”';
                        }
                        if (!isset($rs['setting']['item_inter'][$cache['now']]['content'])) {
                                return '抱歉，数据读取错误(-3)';
                        }
                        //记录参与游戏
                        if (strtolower($text) == strtolower($rs['setting']['item_inter'][$cache['now']]['content'])) {//答案正确
                                //送出积分
                                $credit = isset($rs['setting']['item_inter'][$cache['now']]['credit_add']) ? $rs['setting']['item_inter'][$cache['now']]['credit_add'] : 0;
                                if ($credit) {
                                        D('member')->setUserScore(array('uid' => $this->info['uid'], 'act' => 1, 'event' => 2, 'fid' => $rs['id'], 'credit' => $credit, 'content' => '互动答题:' . $rs['title']));
                                }
                                $note = "完全正确！\n";
                                if ($cache['now'] == $cache['total']) {//如果是最后一个问题，记录玩的次数
                                        if ($credit) {
                                                $note .="奉上积分" . $credit . "个，";
                                        }
                                        if ($rs['setting']['total']) {//有奖品设置信息
                                                $lucky = $this->getLuckData($rs);
                                                if ($lucky['isprize']) {
                                                        $note .= isset($this->eventConfig['ok_result']) ? str_replace('{prize}', $lucky['prize'] . $lucky['gift'], $this->eventConfig['ok_result']) : "哇塞，恭喜您中奖了！！\n中奖信息：\n获得 “" . $lucky['prize'] . "”\n奖品为：" . $lucky['gift'] . "\n中奖码：\n" . $lucky['code'] . "\n注意事项：\n" . $lucky['content'];
                                                        $flag = 1; //星标信息
                                                } else {
                                                        $note .= isset($this->eventConfig['ok_result_no_prize']) ? $this->eventConfig['ok_result_no_prize'] : "很遗憾，您没有中奖，感谢您的参与，请您继续关注后续精彩活动";
                                                }
                                        } else {
                                                $note .="今日题目全部答完了，下次继续吧~";
                                                $this->setUserPrizeInfo(array('id' => $rs['id'], 'code' => '', 'prize' => ''));
                                        }
                                        cacheApi::delete($this->info['key']); //删除缓存信息
                                } else {//继续下一题
                                        $cache['now']+=1;
                                        $cache['isok']+=1;
                                        cacheApi::set($this->info['key'], $cache, 60 * 10); //更新信息
//                    $note.='';
                                        if ($credit) {
                                                $note.="完全正确，您已获得" . $credit . "个积分，继续吧！\n";
                                        }
                                        if (isset($this->eventConfig['list'][$cache['now']])) {
                                                $note .= $this->eventConfig['list'][$cache['now']];
                                        }
                                        $note .= "\n" . $rs['setting']['item_inter'][$cache['now']]['name'];
                                }
                        } else {//答案错误，扣除积分
                                $credit = isset($rs['setting']['item_inter'][$cache['now']]['credit_del']) ? $rs['setting']['item_inter'][$cache['now']]['credit_del'] : 0;
                                if ($credit) {
                                        D('member')->setUserScore(array('uid' => $this->info['uid'], 'act' => 0, 'event' => 2, 'fid' => $rs['id'], 'credit' => $credit, 'content' => '互动答题:' . $rs['title']));
                                }
                                if ($cache['now'] >= $cache['total']) {
                                        $note = isset($this->eventConfig['end_game']) ? $this->eventConfig['end_game'] : "对不起，回答错误，您今日已经完成全部题目了，下次再来吧...";
                                        cacheApi::delete($this->info['key']); //删除缓存信息
                                } else {
//                $cache['iserror']+=1;
                                        $cache['now']+=1;
//                $cache['isBegin'] = false;
                                        cacheApi::set($this->info['key'], $cache, 60 * 10); //更新信息
//                cacheApi::delete($this->info['key']);
                                        $note = isset($this->eventConfig['error_result']) ? $this->eventConfig['error_result'] : "对不起，回答错误，继续努力吧...\n" . $rs['setting']['item_inter'][$cache['now']]['name'] . "\n---------\n注意：回答问题时只需回复答案前对应的编号即可";
                                }
                        }
                }
                return array('type' => 'text', 'Content' => $note, 'flag' => $flag);
        }

        function checkInterStatus(&$rs, &$cache) {
                $status = array('status' => 0, 'info' => '');
                if ($rs) {
                        if ($rs['isOver']) {
                                $status['info'] = $rs['stime'] > TIME ? '游戏将于' . date('Y-m-d H:i:s', $rs['stime']) . '正式开始' : '您来晚了，游戏已经结束...';
                        }
                        if (!$rs['hasTimes']) {
                                $status['info'] = '抱歉，该游戏只能参加' . $rs['times'] . '次，请继续关注其他活动...';
                        }
                        if (!$rs['hasEveryday']) {
                                $status['info'] = $rs['recontent'];
                        }
                        if (!$rs['hasTimes'] && !$rs['hasEveryday'] && $rs['hasShares']) {
                                //存在分享增加游戏次数的情况
                                M('user_share')->where(array('fid' => $rs['id'], 'uid' => $this->info['uid'], 'type' => 2))->setInc('is_used', 1);
                                $status['info'] = '';
                        }
                        if (!isset($rs['setting']['item_inter'][$cache['now']])) {
                                $status['info'] = '额，好像出了点问题...';
                        }
                } else {
                        $status['info'] = '额，活动不存在...';
                }
                if ($status['info']) {
                        cacheApi::delete($this->info['key']);
                } else {
                        $status['status'] = 1;
                }
                return $status;
        }

}
